package com.example.imageviewdemo;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private int[] imgIds = {R.drawable.lijiang, R.drawable.qiao, R.drawable.shuangta, R.drawable.shui, R.drawable.xiangbi};
    private int imgIndex = 0;
    private ImageView imgView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.image_layout);
        setContentView(R.layout.activity_main);
        imgView = findViewById(R.id.img);
        Button btnNext = findViewById(R.id.btn_next);
        Button btnAdd = findViewById(R.id.add);
        Button btnMinus = findViewById(R.id.minus);

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgIndex = (++imgIndex) % imgIds.length;
                imgView.setImageResource(imgIds[imgIndex]);
            }
        });
        btnAdd.setOnClickListener(new SetAlphaListener());
        btnMinus.setOnClickListener(new SetAlphaListener());

        imgView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Bitmap bmp = ((BitmapDrawable) imgView.getDrawable()).getBitmap();
                int x = (int) (motionEvent.getX() / imgView.getWidth() * bmp.getWidth());
                int y = (int) (motionEvent.getY() / imgView.getHeight() * bmp.getHeight());
                int width = 100, height = 100;
                x -= width / 2;
                y -= height / 2;
//                x = Math.min(x, bmp.getWidth() - width);
                x = x > bmp.getWidth() - width ? bmp.getWidth() - width : x;
                y = y > bmp.getHeight() - height ? bmp.getHeight() - width : y;
                x = Math.max(x, 0);
                y = Math.max(y, 0);
                Bitmap localBmp = Bitmap.createBitmap(bmp, x, y, width, width);
                ImageView localImageView = findViewById(R.id.img_local);
                localImageView.setImageBitmap(localBmp);
                return false;
            }
        });
    }

    class SetAlphaListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.add) {
                float alpha = imgView.getAlpha() - 0.1f;
                imgView.setAlpha(alpha);
            }
            if (v.getId() == R.id.minus) {
                float alpha = imgView.getAlpha() + 0.1f;
                imgView.setAlpha(alpha);
            }
        }
    }
}